﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using HandyControl.Data;
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.WPF;
using MeasureAbstract.Base;
using MeasureAbstract.IFarfieldMeasure;
using MeasureAbstract.IMotionDevice;
using MeasureAbstract.ISilentAreaMeasure;
using MeasureLibrary.SilentAreaMeasure;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using LiveChartsCore.SkiaSharpView.VisualElements;
using LiveChartsCore.Kernel;
using System.Windows.Documents;
using NPOI.SS.Formula;
using System.Windows.Controls;
using 紧缩场反射面装调测试系统.Views;
using MeasureAbstract.IVectorNetworkAnalyzer;
using HarfBuzzSharp;
using System.Text.RegularExpressions;
using Org.BouncyCastle.Bcpg.OpenPgp;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;

namespace 紧缩场反射面装调测试系统.ViewModels
{
    public partial class DirectionalPatternTestViewModel : ObservableObject
    {
        private ISilentAreaMeasure? _Measure;
        public ISilentAreaMeasure? Measure
        {
            get { return _Measure; }
            set { SetProperty(ref _Measure, value); }
        }

        public DirectionalPatternTestViewModel()
        {
            LVC.Title = new LabelVisual
            {
                Text = DataType,
                TextSize = 25,
                Padding = new LiveChartsCore.Drawing.Padding(15),
                Paint = new SolidColorPaint(SKColors.DarkSlateGray)

            }; 
        }

        

        public CartesianChart LVC { get; set; } = new CartesianChart();


        #region 关于图表的操作


        [RelayCommand]
        public void AddLine(string Name)
        {
            //设置曲线的属性（名称一般设置为频率值）
            //设置曲线的数据
            //将曲线添加到图表数据
            bool Y = false;
            foreach(var temp in LVC.Series)
            {
                if(temp.Name==Name)
                {
                    //曲线已存在
                    Y = true;
                }
            }

            if(!Y)
            {
                var aaa=LVC.Series.ToList();
                //添加曲线
                aaa.Add(
                    new LineSeries<DataItem>
                    {
                        GeometrySize = 0,
                        Name = Name,
                        Fill=null,
                        Values = Measure.DataDictFrequency_PositionCollection[double.Parse(Name)],
                    }
                    ); 
                LVC.Series = aaa.ToArray();
                SwitchVariable(DataType);

            }

        }

        

        [ObservableProperty]
        public ObservableCollection<string> frequencyList = new ObservableCollection<string>();

        [ObservableProperty]
        public ObservableCollection<string> selectFrequencyList = new ObservableCollection<string>();

        [ObservableProperty]
        public ObservableCollection<string> dataTypeList = new ObservableCollection<string>();

        private string dataType = "";
        public string DataType
        {
            get
            {
                return dataType;
            }
            set
            {
                SetProperty(ref dataType, value);
                SwitchVariable(dataType);
            }
        }

        [RelayCommand]
        public void RemoveLine(string Name)
        {
            //根据名称找到曲线（名称一般设置为频率值）
            //移除曲线
            bool Y = false;
            var A = LVC.Series.ToList();
            foreach (var temp in A)
            {
                if (temp.Name == Name)
                {
                    //曲线已存在
                    Y = true;
                    A.Remove(temp);
                    LVC.Series = A.ToArray();
                    break;
                }
            }

           
        }

        [RelayCommand]
        public void SwitchVariable(string Name)
        {
            //变更图表显示的变量
            //更改图表标题
            //查找当前有几条曲线，记录下来
            //将新曲线的数据添加到图表
            if(Name=="对数幅度")
            {
                var bb = LVC.Title as LabelVisual;
                bb.Text = Name;
              
                foreach (var temp in LVC.Series)
                {
                    var temp2 = temp as LineSeries<DataItem>;
                    temp2.Mapping = (city, chartPoint) =>
                    {
                        return new Coordinate(city.Position, city.LogarithmicAmplitude);
                    };
                }

            }
            else if (Name == "相位")
            {
                var bb = LVC.Title as LabelVisual;
                bb.Text = Name;
                foreach (var temp in LVC.Series)
                {
                    var temp2 = temp as LineSeries<DataItem>;
                    temp2.Mapping = (city, chartPoint) =>
                    {
                        return new Coordinate(city.Position, city.Phase);
                    };
                }
            }
            else
            {
                //throw new Exception("图表不支持的mapper");
            }

        }


        [RelayCommand]
        public void SelectChange(SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                foreach (var item in e.AddedItems)
                {
                    AddLine(item.ToString());
                }
            }

            if (e.RemovedItems.Count > 0)
            {
                foreach (var item in e.RemovedItems)
                {
                    RemoveLine(item.ToString());
                }
            }
        }


        #endregion



        [RelayCommand]
        public void Stop()
        {
            Measure.MeasureStop();
        }
        [RelayCommand]
        public void Pause()
        {
            Measure.MeasurePause();
        }

        [RelayCommand]
        public void Continue()
        {
            Measure.MeasureContinue();
        }


        [RelayCommand]
        public async void Start(object Type)
        {
            if(Measure.Flag.TestingFlag)
            {
                HandyControl.Controls.Growl.Info("正在测试，请稍后!");
                return;
            }
            Measure.Flag.TestingFlag = true;
            //初始化数据类型列表
            DataTypeList.Clear();
            var VNA = Measure.DeviceList[1] as IVectorNetworkAnalyzer;
            foreach(var temp in VNA.SelectedDataFormats)
            {
                DataTypeList.Add(temp);
            }

            //初始化频点列表
            FrequencyList.Clear();
            //计算频点列表
            if (VNA.SeMode)
            {
                //平均
                FrequencyList = new ObservableCollection<string>();
                FrequencyList.Clear();
                double step = (VNA.GetHZ(VNA.EndFrequency, VNA.EndFrequencyUnit) - VNA.GetHZ(VNA.StartFrequency, VNA.StartFrequencyUnit)) / (VNA.FrequencyCount - 1);
                for (int i = 0; i < VNA.FrequencyCount; i++)
                {
                    FrequencyList.Add((VNA.GetHZ(VNA.StartFrequency, VNA.StartFrequencyUnit) + step * i).ToString());
                }

            }
            if (VNA.CbMode)
            {
                FrequencyList = new ObservableCollection<string>();
                FrequencyList.Clear();
                double step = (VNA.GetHZ(VNA.BandFrequency, VNA.BandFrequencyUnit)) / (VNA.FrequencyCount - 1);
                for (int i = 0; i < VNA.FrequencyCount; i++)
                {
                    FrequencyList.Add((VNA.GetHZ(VNA.CenterFrequency, VNA.CenterFrequencyUnit) - VNA.GetHZ(VNA.BandFrequency, VNA.BandFrequencyUnit) / 2 + step * i).ToString());
                }
            }
            if (VNA.ListMode)
            {
                FrequencyList = new ObservableCollection<string>();
                FrequencyList.Clear();
                foreach (var temp in VNA.Frequencys.Replace("，", ",").Split(","))
                {
                    FrequencyList.Add((VNA.GetHZ(double.Parse(Regex.Replace(temp, "[^0-9]", "")), Regex.Replace(temp, "[^a-zA-Z]", ""))).ToString());

                }
            }

            
            //给测量中的频点列表赋值
            Measure.FrequencyList = new ObservableCollection<double>();
            foreach(var temp in FrequencyList)
            {
                Measure.FrequencyList.Add(double.Parse(temp));
            }


            //构建数据记录对象
            if (Measure.MeasureData.DataItems == null)
            {
                Measure.MeasureData.DataItems = new ObservableCollection<DataItem>();
            }
            else
            {
                Measure.MeasureData.DataItems.Clear();
            }
            Measure.MeasureData.MeasurementTime = DateTime.Now.ToString("F");
            Measure.MeasureData.MeasurementType = "";
            Measure.MeasureData.MeasurementParameter = VNA.SParameter;
            Measure.MeasureData.DataFormat = "";
            foreach (var Temp in VNA.SelectedDataFormats)
            {
                Measure.MeasureData.DataFormat += Temp + ";";
            }
            Measure.MeasureData.AntennaIdentification = Measure.AntennaName + ";" + Measure.AntennaModel;
            Measure.MeasureData.PolarizationDirection = Measure.PolarizationDirection;
            Measure.MeasureData.Note = Measure.Note;


            //初始化数据 在初始化的时候已经有了
            if (Measure.DataDictFrequency_PositionCollection==null)
            {
                Measure.DataDictFrequency_PositionCollection = new Dictionary<double, ObservableCollection<DataItem>>();
            }
            Measure.DataDictFrequency_PositionCollection.Clear();
            Measure.DataDictFrequency_PositionCollection.Add(double.Parse(FrequencyList[0]), new ObservableCollection<DataItem>());

            if (Measure.DataDictPosition_FrequencyCollection == null)
            {
                Measure.DataDictPosition_FrequencyCollection = new Dictionary<double, ObservableCollection<DataItem>>();
            }
            else
            {
                Measure.DataDictPosition_FrequencyCollection.Clear();
            }


            //选中第一个数据类型和频点
            DataType = DataTypeList[0];
            SelectFrequencyList = new ObservableCollection<string>() { FrequencyList[0] };



            await Measure.MeasureStart(Type);
            HandyControl.Controls.Growl.Info("测试完成!");
            SaveData(null);
            Measure.Flag.TestingFlag = false;
        }
        [RelayCommand]
        public void SaveData(object Type)
        {
            Measure.SaveData(Type);
            HandyControl.Controls.Growl.Info($"{Measure.DataFilePath}保存成功!");
        }


        [RelayCommand]
        public void Transfer(object Name)
        {
            if(Name != null)
            {
                if(Name.ToString()=="数据处理")
                {
                    DataProcess.ViewModel.LoadData(Measure.MeasureData);
                    MainWindow.ViewModel.NavigationPage(Name.ToString());
                }

                if (Name.ToString() == "结果分析")
                {
                    ResultAnalysis.ViewModel.LoadData(Measure.MeasureData);
                    MainWindow.ViewModel.NavigationPage(Name.ToString());
                }
            }
        }
    }
}
